const express = require('express');
const router = express.Router();
const jobsMapper = require('../mapper/jobsMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');

router.post('/v1/job', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { userId, jName, jAvatar, startTime, endTime, minDuration, region, jAddress, position, areas, rights, jType, salary, content } = req.body;
  if(userId != validate) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }

  const items = [ userId, jName, jAvatar, startTime, endTime, minDuration, region, jAddress, position, areas, rights, jType, salary, content ];
  conn.query(jobsMapper.add, items, (err, data) => {
    if(err) {
      res.send({ code: 200, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.put('/v1/job', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { jName, jAvatar, startTime, endTime, minDuration, region, jAddress, position, areas, rights, jStatus, salary, content, id } = req.body;
  const items = [ jName, jAvatar, startTime, endTime, minDuration, region, jAddress, position, areas, rights, jStatus, salary, content, id ];
  conn.query(jobsMapper.update, items, (err, data) => {
    if(err) {
      res.send({ code: 200, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  });
});

router.get('/v1/job', (req, res) => {
  const { jName, startTime, userId, jStatus, page, size } = req.query;
  const items = [ jName, jName, jName, jName, jName, jName, jName, jName, startTime, startTime, userId, userId, jStatus, jStatus, (page - 1) * size, size ];

  conn.query(jobsMapper.select, items, (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      items.splice(items.length -  2, 2);
      conn.query(jobsMapper.count, items, (err, result) => {
        if(err) {
          res.send({ code: 500, err });
        } if(result && result.length) {
          res.send({ code: 200, data, count: result[0].total });
        }
      });
    }
  });
});

router.get('/v1/job/:id', (req, res) => {
  const id = req.params.id;
  conn.query(jobsMapper.detail, [ id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data: data[0] });
    }
  });
});

module.exports = router;